<?php

class ImController  extends AppController{

	public function beforeFilter() {
	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; 
	    $this->C_auth->allowedActions = array('index','ajax','getfile');

	}

	public function index() {
        $session_uid = $this->C_session->read('Auth.user.id');
        if(!$session_uid) {exit();}	//没有session_uid退出	
		$uid = $this->C_session->read('pspim.uid');
		if($uid!=$session_uid) {
			$uid = '';	//解决 $session_uid 来自cookie 造成 id 不相等的问题
		}	
        if(!$uid) {	
			$query = array(
				'conditions' => array('user.id' => $session_uid), 
				'fields' => array('user.id','user.username','user.user_ico'), 
			);
			$row = POP::exe('[@@:UM user][@@:QU find:first]',$query);//得到主系统中的用户信息          			
			if($row) {
			    $row = $row['user'];				
				$row['uid'] = $row['id'];
				$row['u_name'] = $row['username'];
				$row['u_ico'] = $row['user_ico'];				
				$row['line_status'] = 1;
				$row['msg_wav'] = 1;
				$uid = $row['uid'];			// 通过接口获取uid, 判断是否已登陆
			}
			if(!$uid) {						// 未登陆不显示im
				exit();
			}

	        $user_row = $this->get_user_info($uid); 
			$group = $this->get_group_list($uid);
			$this->change_status(1,$uid);	// 更新用户状态为在线
			if(!$user_row) {
				!$row['u_ico'] && $row['u_ico'] = 'images/d_ico_0_small.gif';
				$this->insert_user_info($row);
			} else {
				$row['msg_wav'] = $user_row['msg_wav'];
				// 更新用户信息
				$query  = array();		
				$query['keyid'] = true;
				$safeData['chatuser'] = array('u_name'=>$row['u_name'],'u_ico'=>$row['u_ico'],'line_status'=>1);				
				$query['set'] = $safeData;	
				$query['conditions'] = array('chatuser.uid'=>$uid);			
				if(POP::exe('[@@:UM chatuser][@@:QU save]',$query)	) {
					$query  = array();		
					$query['keyid'] = true;
					$safeData['chatpals'] = array('pals_name'=>$row['u_name'],'pals_ico'=>$row['u_ico'],'line_status'=>1);				
					$query['set'] = $safeData;	
					$query['conditions'] = array('chatpals.pals_id'=>$uid);		
					POP::exe('[@@:UM chatpals][@@:QU save]',$query);				
				}
				$row['u_intro'] = $user_row['u_intro'];
				$row['msg_wav'] = $user_row['msg_wav'];
				$row['online_time'] = $user_row['online_time'];
				$row['addFriends'] = $user_row['addFriends'];
				$row['question'] = $user_row['question'];
				$row['answer'] = $user_row['answer'];
			}		
            $this->C_session->write('pspim.uverifycode', mk_code());
            $this->C_session->write('pspim.uid', $row['uid']);
            $this->C_session->write('pspim.uname', $row['u_name']);
            $this->C_session->write('pspim.ico', $row['u_ico']);
            $this->C_session->write('pspim.status',$row['line_status']);			
		}else {
	        $row = $this->get_user_info($uid);
			$group = $this->get_group_list($uid);		   
		}
        $dir = Loader::build('config');	
		include($dir[0].'/language.php');//导入语言包		
        $this->set('language_basic',$language_basic);
        $this->set('language_talkwin',$language_talkwin);
        $this->set('language_face',$language_face);
        $this->set('language_group',$language_group);
        $this->set('language_friend',$language_friend);
        $this->set('language_transfer',$language_transfer);
        $this->set('language_limit',$language_limit);
        $this->set('language_online',$language_online);
		include($dir[0].'/configuration.php');//导入配置文件	
        $this->set('allowmaxsize',Param::read('im.allowmaxsize'));		
        $this->set('allowtype',$allowtype);		
		
        $this->set('row',$row);
        $this->set('group',$group);		
	}
	
	
	public function getfile() {	
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		$fid = intval(Request::get_args('fid'));
		if($fid<=0){echo404();}	
		
		$query = array(
			'conditions' => array('chattransferfileinfo.id' => $fid), 
			'fields' => array('chattransferfileinfo.*'), 
		);
		$fileinfo = POP::exe('[@@:UM chattransferfileinfo][@@:QU find:first]',$query);		
		$fileinfo = $fileinfo['chattransferfileinfo'];

		if($fileinfo['recipient_id']!=$uid or $fileinfo['is_download']==1){	echo404();}

		$file = $fileinfo['file_url'];
		$fileoldname = $fileinfo['old_name'];
        $dir = Loader::build('config');//导入语言包	
		include($dir[0].'/language.php');//导入语言包
		if(!file_exists($file)){
			echo '<script language="javascript">alert("'.$language_basic['FileIsNotExist'].'");</script>';
			exit();
		}else{
			$filetype = filetype($file);
			$filesize = filesize($file);
			$filename = basename($file);
			header("Pragma: public");
			header('Content-Encoding: none');
			header('Content-Length: '.$filesize);	
			header('Content-Type: '.$filetype);	
			header("Cache-Control: private, post-check=0, pre-check=0,max-age=5");
			$encoded_fileoldname = urlencode($fileoldname);
			$encoded_fileoldname = str_replace("+", "%20", $encoded_fileoldname);
			$ua = getenv(HTTP_USER_AGENT);
			if (preg_match("/MSIE/", $ua)) { 
				header('Content-Disposition: attachment; filename="' . $encoded_fileoldname . '"');
			} else if (preg_match("/Firefox/", $ua)) { 
				header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileoldname . '"');
			} else { 
				header('Content-Disposition: attachment; filename="' . $fileoldname . '"');
			}
			//下载文件
			$download_status = readfile($file);

			//下载完成后..		
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chattransferfileinfo'] = array('is_download'=>1,'download_time'=>time());				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chattransferfileinfo.id'=>$fid);		
			$status = POP::exe('[@@:UM chattransferfileinfo][@@:QU save]',$query);	

		//	unlink($file);
			exit;	
		}		
	}

	public function ajax() {	
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		//ajax 请求操作！
		$actArray = array(
			'loadvideo','language','getfriendlist','getfriendinfo',	'initwin',
			'getmessagelist','postnewmessage','changestatus','changemsgwav',
			'gethistorymessage','createnewgroup','addusertogroup','updatapals',
			'logoutgroup','getgrouplist','addtomyfriend','postfile','getpeerid',
			'getvideostatus','updatepeerid','updatevideostatus','updateintro',
			'uploadheadimg','onlineTime','delFriends','getCustomGroup',
			'moveFriends','newCustomGroup','updateCustomGroup','delCustomGroup',
			'setCondition','getStranger','updateContacted','searchGroup',
			'serachUser','delmsg',
		);		
		$act = $_GET['act'];
		if(in_array($act,$actArray)){
            $dir = Loader::build('config');//导入语言包			
		    include($dir[0].'/configuration.php');//导入配置文件		
		    call_user_func_array(array(&$this, $act), $this->passedArgs);	
		}else {
		    exit('-1');
		}	
    }
	
	public function loadvideo() {	
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		$swfid = Request::get_args('swfid');		
		echo "var so = new SWFObject('".$this->base."/plugins/im/vendors/video/P2PClient.swf', 'P2PClient_".$swfid."', '214', '400', '9', '#ffffff'); 
		so.addParam('allowScriptAccess', 'sameDomain');
		so.addParam('scale', 'noscale');
		so.addParam('menu', 'false');  
		so.addVariable('swfid','".$swfid."');
		so.write('flashcontent_".$swfid."');";
		exit;
	}	
	
	
	public function getfriendlist() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		
		if(isset($_POST['sid'])) {
			$session_id = intval(str_replace('g_','',$_POST['sid']));
		} else {
			$session_id = 0;
		}	
		Loader::import('lib.ctime');
		$ctime = new ctime();
		$time_stamp = $ctime->time_stamp();		
		if($session_id) {		
			$session_info = $this->get_session_info_bysessionid($session_id);
			$pals_id = trim($session_info['player_ids'],',');
			$friendlist = $this->get_group_friend_list($pals_id);
		} else {
			$friendlist = $this->get_friend_list($uid);
		}

		$timeout_user = $this->get_timeout_user($time_stamp);

		if($timeout_user) {
			$this->update_user_to_offline($timeout_user);
		}
		// 更新最后动作时间
		$this->update_user_last_time($uid,$time_stamp);

		if(!$friendlist) {
			exit("-1");
		}

		echo chat_json_encode($friendlist);		
		exit;		
	}

	public function getfriendinfo() {	
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
        $uid = intval(Request::get_args('sid'));
		$userinfo = $this->get_user_info($uid);
		$array = array(
			'pals_id' => $userinfo['uid'],
			'pals_name' => $userinfo['u_name'],
			'pals_ico' => $userinfo['u_ico'],
			'line_status' => $userinfo['line_status'],
			'pals_intro' => $userinfo['u_intro'],
		);
		echo chat_json_encode($array);	
        exit;		
	}
	
	public function initwin() {	
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');		
		/* post 数据处理 */
		$pals_id = Request::get_args("id");

		if(!$pals_id) {
			exit("-1");
		}	

		if(is_numeric($pals_id)) {
			$player_ids = get_player_ids($uid,$pals_id);
			$session_info = $this->get_session_info($player_ids);
		} else {
			$session_id = str_replace("g_","",$pals_id);
			if(is_numeric($session_id)) {
				$session_info = $this->get_session_info_bysessionid($session_id);
			} else {
				exit("-1");
			}
		}


		if(!$session_info) {
			$session_info = $this->insert_new_seesion_info($player_ids);
			$txt_info = $this->insert_new_txt_info($player_ids,$session_info['session_id']);
		} else {
			$this->update_init_pagect_position($session_info['session_id'],$session_info['readed_pagect_position']);	//更新初始 pagect_position
		}

		$verifycode = mk_md5($session_info['session_code'],$uverifycode);
		exit($verifycode);		
	
	}
	
	public function getmessagelist() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		/* post 数据处理 */
		$pals = Request::get_args("pals");

		if(!$pals) {
			exit("-1");
		}
		// pals处理
		$pals_explode = explode("|",$pals);//打开多个聊天对象时将有多个|隔开
		$pals_explode = array_nullclear($pals_explode);

		// 查询session
		$session_list = $this->get_newmsg_friend_list($uid);

		// 如果有新消息 执行如下 
		if($session_list) {
			$get_txt_sql = "";
			$status_new_msg_txt = 0; // 是否有新的消息内容需要提取
			$update_session_arr = array(); // 需要更新用户当前读位置的会话信息
			$or = '';
			foreach($session_list as $value) {
				$return_pals_id = empty($value['group_name']) ? trim(str_replace(','.$uid.',','',$value['player_ids']),',') : "g_".$value['session_id'];
				
				$return_winopen = in_array($return_pals_id,$pals_explode) ? '1' : '-1';
				if($return_winopen=="1"){ 
					$status_new_msg_txt++; 
					$update_session_arr[] = $value;
					$get_txt_sql .= $or." (session_id='".$value['session_id']."' and txt_pagenum>='".$value['page']."') and txt_content!=''";
					$or = ' or ';
				}
				
				$return_value[$value['session_id']] = array(
					'pals_id' => $return_pals_id,
					'winopen' => $return_winopen,
					'message' => '-1',
					'video_status' => $value['video_status'],
				);
				$pagects[$value['session_id']] = array($value['page'],$value['ct']);
			}
            $txt_split_lenght = Param::read('im.txt_split_lenght');
			// 如果有新的消息内容需要提取
			if($status_new_msg_txt>0) {
				// 查询需要提取的新消息txt记录
				$sql ="[@@:UM chattxt][@@:QU select][_select chattxt.* ][_from][_table chattxt:yes][_where $get_txt_sql ][_order txt_pagenum asc]";	
                $txt_list = POP::exe($sql);					
				$message_arr = array();
				$split_arr = array();
				foreach($txt_list as $value) {
				    $value = $value['chattxt'];
					if($value['using']==1 && $value['txt_length']>=$txt_split_lenght) {
						$split_arr[$value['player_ids']] = array(
							'id' => $value['id'],
							'multi_chat' => $value['multi_chat'],
							'player_ids' => $value['player_ids'],
							'session_id' => $value['session_id'],
							'txt_pagenum' => $value['txt_pagenum']+1,
							'txt_ctnum' => 1,
							'txt_content' => '',
							'txt_length' => '0',
							'txtlog_pageview' => $value['player_ids']
						);
					}

					// 格式化聊天记录， 并存放到 message_arr
					$formatv = format_message($pagects[$value['session_id']],$value);
					
					if(isset($message_arr[$value['session_id']])) {
						$message_arr[$value['session_id']] = array_merge($message_arr[$value['session_id']],$formatv);
					} else {
						$message_arr[$value['session_id']] = $formatv;
					}
				}
				
				// 形成最终数组 $return_value;
				foreach($message_arr as $key=>$value) {
					if($value) {
						$return_value[$key]['message'] = $value;
					}
				}

				foreach($update_session_arr as $value) {
					$this->update_readed_pagect_position($uid,$value);
				}

				if($split_arr) {
					// 需要折分新记录
					$this->split_txt_content($split_arr);
				}
			}
			//$return_value = clear_array_numkey($return_value);
			sort($return_value);
			echo chat_json_encode($return_value);

		} else {
			exit("-1");
		}		
		exit;	
	}
	
	public function postnewmessage() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		/* post 数据处理 */
		$pals_id = Request::get_args("pals");
		$v = short_check(Request::get_args("v"));
		$vc = short_check(Request::get_args('vc'));
		$session_id = '';

		if(!$pals_id && !$v && !$vc) {
			exit("-1");
		}
		
		if(is_numeric($pals_id)) {
			$player_ids = get_player_ids($uid,$pals_id);
			$session_info = $this->get_session_info($player_ids);
		} else {
			$session_id = str_replace("g_","",$pals_id);
			if(is_numeric($session_id)) {
				$session_info = $this->get_session_info_bysessionid($session_id);
			} else {
				exit("-1");
			}
		}
		if(is_numeric($pals_id)) {
			if(!$session_info) {
				$userinfo = $this->get_user_info($uid);
				$session_info = $this->insert_new_seesion_info($player_ids);
				$this->insert_new_txt_info($player_ids,$session_info['session_id']);
			} else {
				$checktxt = $this->imIsExistTxt($session_info['session_id']);
				if(!$checktxt) {
					$split_arr[$session_info['player_ids']] = array(
						'id' => '',
						'multi_chat' => '0',
						'player_ids' => $session_info['player_ids'],
						'session_id' => $session_info['session_id'],
						'txt_pagenum' => $session_info['page_num']+1,
						'txt_ctnum' => 1,
						'txt_content' => '',
						'txt_length' => '0',
						'txtlog_pageview' => $session_info['player_ids']
					);
					$this->split_txt_content($split_arr);
				}	
			}
		}
		if(!strstr($session_info['player_ids'],",$uid,")) { exit("-1");}
		if(mk_md5($session_info['session_code'],$uverifycode)!=$vc) { exit("-1");}

		Loader::import('lib.ctime');
		$ctime = new ctime();
		$datatime = $ctime->long_time();

		$v = str_replace("\n","<br />",$v);
		$v = str_replace('"',"&quot;",$v);
		$pattern = "/{img:(.+?)\/}/";
		$replacement = "<img src=\"\${1}\" />";
		$v = preg_replace($pattern, $replacement, $v);
		$txt_content = $uid.'{'.$datatime.'}'.$v;

		$txt_length = strlen($txt_content);

		if(is_numeric($pals_id)) {
			$player_ids = get_player_ids($uid,$pals_id);
			$post_txt = $this->post_txt($player_ids,$txt_content,$txt_length);
		} else {//群聊天
			$session_id = str_replace("g_","",$pals_id);
			if(is_numeric($session_id)) {
				$post_txt = $this->post_txt_bysessionid($session_id,$txt_content,$txt_length);
			} else {
				exit("-1");
			}
		}

		if($post_txt) {
			if(is_numeric($session_id)) {//群聊天
				$this->update_session_ctnum_bysessionid($session_id);
			} else {//个人聊天
				$this->update_session_ctnum($player_ids);
			}
			exit("1");
		} else {
			exit("-1");
		}		
		
		
		
    }	
		
	public function changestatus() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		/* post 数据处理 */
		$v = intval(Request::get_args("s"));
		if($this->change_status($v,$uid)) {
			exit("1");
		} else {
			exit("-1");
		}		
		
    }

    // 改变信息提示音状态
	public function changemsgwav() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		/* post 数据处理 */
		$v = intval(Request::get_args("v"));	

		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatuser'] = array('msg_wav'=>$v);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatuser.uid'=>$uid);		
		if(POP::exe('[@@:UM chatuser][@@:QU save]',$query)) {
			exit("1");
		} else {
			exit("-1");
		}
    }
	
	public function gethistorymessage() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		/* post 数据处理 */
		$pals = Request::get_args("pals");
		$page = intval(Request::get_args('page'));
		if(!$pals) {
			exit("-1");
		}

		// 创建sql
		if(strstr($pals,"g_")) {
			$session_id = intval(str_replace("g_",'',$pals));			
		    $sql ="[@@:UM chattxt][@@:QU select][_select chattxt.* ][_from][_table chattxt:yes][_where session_id='$session_id' and INSTR(txtlog_pageview,',$uid,') and txt_content!='' ORDER BY txt_pagenum asc ]";			

		} else {
			$player_ids = get_player_ids($uid,$pals);
		    $sql ="[@@:UM chattxt][@@:QU select][_select chattxt.* ][_from][_table chattxt:yes][_where player_ids='$player_ids' and INSTR(txtlog_pageview,',$uid,') and multi_chat='0' and txt_content!='' ORDER BY txt_pagenum asc ]";			
		}
		$result = POP::exe($sql);	
		// 统计条数
		$countpage = count($result);
		if(!$page || $page > $countpage) {
			$page = $countpage;
		}

		// 创建返回新数组
		$newarray = array(
			'countpage' => $countpage,
			'page' => $page,
			'message' => ''
		);
		foreach($result as $key=>$value) {
		    $value = $value['chattxt'];
			if(($key+1)==$page){
				$newarray['tid'] = $value['id'];
				$newarray['message'] = format_message(array(0,0),$value);
			}
		}
		if($newarray['message']) {
			echo chat_json_encode($newarray);
		} else {
			exit("-1");
		}		
		exit;
		
		
    }		
	
	public function createnewgroup() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
	
		/* post 数据处理 */
		$groupname = Request::get_args("gname");
		$m = Request::get_args('m');

		if(!$groupname) {
			exit("-1");
		}

		if($session_id = $this->create_new_group($uid,$groupname,$m)) {
			$array['host_id'] = $uid;
			$array['pals_id'] = "g_".$session_id; //substr($v['player_ids'],1,-1);
			$array['group_name'] = $groupname;
			$array['pals_name'] = $groupname;
			$array['pals_ico'] = $this->base."images/talk.gif";
			$array['line_status'] = "1";
			$array['num'] = 1;
			$array['group_mid'] = $uid;
			echo chat_json_encode($array);
			exit();
		} else {
			exit("-1");
		}	
	}
	
	
	public function addusertogroup() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');

		/* post 数据处理 */
		$pals_ids = Request::get_args("pid");
		$gid = Request::get_args("gid");

		if(!$pals_ids || !$gid) {
			exit("-1");
		}

		$session_id = intval(str_replace('g_','',$gid));
		if(!$session_id) {
			exit("-1");
		}

		$session_info = $this->get_session_info_bysessionid($session_id);
		$add_arr = array();
		if($session_info) {
			// 处理 player_ids, 相关好了update
			$player_ids = $session_info['player_ids'];
			$player_id_arr = explode(",",trim($player_ids,', '));
			$init_pagect_position_arr = explode(",",$session_info['init_pagect_position']);
			$readed_pagect_position_arr = explode(",",$session_info['readed_pagect_position']);

			$pals_id_arr = explode(",",trim($uid.$pals_ids,', '));
			if(count($pals_id_arr)>30) {
				exit("2");
			}
			$arr2 = array_diff($player_id_arr,$pals_id_arr);
			$arr3 = array_diff($pals_id_arr,$player_id_arr);

			if($arr2) {
				foreach($player_id_arr as $k=>$v) {
					if(in_array($v,$arr2)) {
						$init_pagect_position_arr[$k] = '';
						$readed_pagect_position_arr[$k] = '';
						$player_id_arr[$k] = '';
					}
				}
			}
			if($arr3) {
				$position = $session_info['page_num']."->".$session_info['ct_num'];
				foreach($arr3 as $v) {
					$player_id_arr[] = $v;
					$init_pagect_position_arr[] = $position;
					$readed_pagect_position_arr[] = $position;
				}
			}

			$update_session['player_ids'] = ','.implode(",",array_nullclear($player_id_arr)).',';
			$update_session['init_pagect_position'] = implode(",",array_nullclear($init_pagect_position_arr));
			$update_session['readed_pagect_position'] = implode(",",array_nullclear($readed_pagect_position_arr));
			
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chatsession'] = $update_session;				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chatsession.session_id'=>$session_id);		
			if(POP::exe('[@@:UM chatsession][@@:QU save]',$query)){				
				$query  = array();		
				$query['keyid'] = true;
				$safeData['chattxt'] = array('player_ids'=>$update_session['player_ids'],'txtlog_pageview'=>$update_session['player_ids']);				
				$query['set'] = $safeData;	
				$query['conditions'] = array('chattxt.session_id'=>$session_id,'chattxt.using'=>1);		
				POP::exe('[@@:UM chattxt][@@:QU save]',$query);				
			}
			echo "1";
		} else {
			exit("-1");
		}		
		exit;		
	}
	
	public function updatapals() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	

		$pals = $this->get_friend_list($uid);
		$getMainFriend = Param::read('im.getMainFriend');
		//同步好友关系
		if($getMainFriend){
			$api_pals = $this->get_api_pals_list();
		}

		if(!isset($api_pals)) { exit("-1"); }

		$new_pals_array = array();
		if($pals) {
			foreach($pals as $value) {
				$new_pals_array[] = $value['pals_id'];
			}
		}

		$api_new_array = array();
		$uids = array();
		foreach($api_pals as $value) {
			if(!in_array($value['uid'],$new_pals_array)) {
				$api_new_array[] = $value;
				$uids[] = $value['uid'];
			}
		}

		if($api_new_array) {
			$query = array(
				'conditions' => array('chatuser.uid' => $uids), 
				'fields' => array('chatuser.*'), 
			);
			$user_row = POP::exe('[@@:UM chatuser][@@:QU find:all]',$query);				
			$user_array = array();
			$insert_user_info = array();
			
			if($user_row) {
				foreach($user_row as $value) {
				    $value = $value['chatuser'];
					$user_array[$value['uid']] = clear_array_numkey($value);
				}
			}
			
			foreach($api_new_array as $v) {
				if(!isset($user_array[$v['uid']])) {
					$temp = $v;
					$temp['line_status'] = 0;
					$insert_user_info[] = $temp;		// 需要插入的用户信息
				}
			}


			if($insert_user_info) {
				foreach($insert_user_info as $value) {
					$value['line_status'] = intval($value['line_status']);
					$this->insert_user_info($value);
				}
			}

			foreach($api_new_array as $value) {
				$insert_array = array(
					'host_id' => $uid,
					'pals_id' => $value['uid'],
					'pals_name' => $value['u_name'],
					'pals_ico' => $value['u_ico'],
					'line_status' => intval($value['line_status'])
				);
				
				if($user_array[$value['uid']]) {
					$insert_array['line_status'] = $user_array[$value['uid']]['line_status'];
				}

				$this->insert_friend_info($insert_array);
			}

		} else {
			exit("-1");
		}		

    }		

	public function logoutgroup() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	

		/* post 数据处理 */
		$gid = Request::get_args("gid");
		$session_id = intval(str_replace('g_','',$gid));
		if(!$session_id) {
			exit("-1");
		}

		$session_info = $this->get_session_info_bysessionid($session_id);
		$add_arr = array();
		if($session_info) {
			$player_ids = $session_info['player_ids'];
			if(strpos($player_ids, ",".$uid.",")==0) {
				//删除好友关系记录
				$query = array('conditions'=>array('chatsession.session_id' => $session_id));			
				if(POP::exe('[@@:UM chatsession][@@:QU del]',$query)) {
					//删除聊天记录
					$query = array('conditions'=>array('chattxt.session_id' => $session_id));				
					POP::exe('[@@:UM chattxt][@@:QU del]',$query);
				} else {
					exit(-1);
				}
			} else {
				$player_id_arr = explode(",",trim($player_ids,', '));
				$init_pagect_position_arr = explode(",",$session_info['init_pagect_position']);
				$readed_pagect_position_arr = explode(",",$session_info['readed_pagect_position']);
				foreach($player_id_arr as $k=>$v) {
					if($v==$uid) {
						$init_pagect_position_arr[$k] = '';
						$readed_pagect_position_arr[$k] = '';
						$player_id_arr[$k] = '';
					}
				}

				$update_session['player_ids'] = ','.implode(",",array_nullclear($player_id_arr)).',';
				$update_session['init_pagect_position'] = implode(",",array_nullclear($init_pagect_position_arr));
				$update_session['readed_pagect_position'] = implode(",",array_nullclear($readed_pagect_position_arr));
				
				$query  = array();		
				$query['keyid'] = true;
				$safeData['chatsession'] = $update_session;				
				$query['set'] = $safeData;	
				$query['conditions'] = array('chatsession.session_id'=>$session_id);		
				if(POP::exe('[@@:UM chatsession][@@:QU save]',$query)){				
					$query  = array();		
					$query['keyid'] = true;
					$safeData['chattxt'] = array('player_ids'=>$update_session['player_ids'],'txtlog_pageview'=>$update_session['player_ids']);				
					$query['set'] = $safeData;	
					$query['conditions'] = array('chattxt.session_id'=>$session_id,'chattxt.using'=>1);		
					POP::exe('[@@:UM chattxt][@@:QU save]',$query);						
					
				} else {
					exit(-1);
				}
			}
			echo "1";
		} else {
			exit("-1");
		}
		exit;
    }	
	
	public function getgrouplist() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		$group = $this->get_group_list($uid);
		if(!$group) {
			exit("-1");
		}
		echo chat_json_encode($group);
		exit;
    }

	
	
	public function addtomyfriend() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');		

		$return = array();
		/* post 数据处理 */
		$pals_id = intval(str_replace("imWin_",'',Request::get_args("uid")));
		$answer = short_check(Request::get_args('answer'));

		if(!$pals_id) {
			$return[0] = "-4";
			echo chat_json_encode($return);
			exit;
		}


		$pals_info = $this->get_user_info($pals_id);

		$query = array(
			'conditions' => array('chatpals.host_id' => $uid,'chatpals.pals_id' => $pals_id), 
			'fields' => array('chatpals.*'), 
		);
		$row = POP::exe('[@@:UM chatpals][@@:QU find:first]',$query);		
		if($row) {
			$return[0] = "-1";
			echo chat_json_encode($return);
			exit;
		}
		if($pals_info) {
			$array = array(
				'host_id' => $uid,
				'pals_id' => $pals_info['uid'],
				'pals_name' => $pals_info['u_name'],
				'pals_ico' => $pals_info['u_ico'],
				'line_status' => $pals_info['line_status']
			);
			switch($pals_info['addFriends']) {
				case 3:			//拒绝加为好友
					$return[0] = "-3";
					echo chat_json_encode($return);
					exit;
					break;
				case 2:			//回答问题
					if(!$answer){
						$return[0] = "-2";
						$return[1] = $pals_info['question'];
						echo chat_json_encode($return);
						exit;
					} else {
						$query = array(
							'conditions' => array('chatuser.uid' => $pals_id,'chatuser.answer' => $answer), 
							'fields' => array('chatuser.*'), 
						);
						$row = POP::exe('[@@:UM chatuser][@@:QU find:first]',$query);						
						if($row){
							if($this->insert_friend_info($array)){
								$return[0] = "1";
								echo chat_json_encode($return);
								exit;
							} else {
								$return[0] = "-4";
								echo chat_json_encode($return);
								exit;
							}
						} else {
							$return[0] = "-5";
							echo chat_json_encode($return);
							exit;
						}
					}
					break;
			}
			if($this->insert_friend_info($array)) {
				$return[0] = "1";
				echo chat_json_encode($return);
				exit;
			} else {
				$return[0] = "-4";
				echo chat_json_encode($return);
				exit;
			}
		} else {
			$return[0] = "-4";
			echo chat_json_encode($return);
			exit;
		}


		
	}
	

	public function postfile() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
        Loader::import('lib.cupload');
        $dir = Loader::build('config');//导入语言包	
		include($dir[0].'/language.php');//导入语言包	
		$allowmaxsize = Param::read('im.allowmaxsize');
		$allowtype = array (
		  0 => 'jpg',
		  1 => 'gif',
		  2 => 'png',
		  3 => 'zip',
		  4 => 'rar',
		);		
		$upfile = Request::get_args('upfile');
		$pid = Request::get_args('pid');
		if(!$upfile || !$uid || !$pid) {
			exit("-1");
		}
		if($upfile==2){	//发送图片
			$allowtype = array('jpg','gif','png','bmp');
			$userfiledir = 'uploadfiles/customimg/'.date('Y').'/'.date('m').'/'.date('d').'/'.$uid;
		}else {
			$userfiledir = 'uploadfiles/customimg/'.date('Y').'/'.date('m').'/'.date('d').'/'.$uid;		
		}
		
		if($upfile == 1 or $upfile == 2){
			$upload = new upload($userfiledir,$allowtype,$allowmaxsize);
			$upfileAry = $upload->save('impostfile');
			switch($upfileAry){
				case 1:
					echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['FileNotExist']."');</script>";
					exit;
					break;
				case 2:
					echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['OutRestraint']."');</script>";
					exit;
					break;
				case 3:
					echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['UnknowType'].implode(',',$allowtype)."');</script>";
					exit;
					break;
				case 4:
					echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['TransferFailed']."');</script>";
					exit;
					break;
				case 5:
					echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['TransferFailed']."');</script>";
					exit;
					break;
				case 6:
					echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['TransferFileOff']."');</script>";
					exit;
					break;
			}	
		}else{
			echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['TransferFileOff']."');</script>";
			exit;
		}
		if(is_array($upfileAry)) {
			$insert_array = array(
				'promoter_id'	=>	$uid,
				'recipient_id'	=>	$pid,
				'file_url'		=>	$upfileAry['filename'],
				'is_download'	=>	0,
				'upload_time'	=>	time(),
				'download_time'	=>	0,
				'old_name'		=>	$upfileAry['oldname'],
			);
			if($upfile==2){
				$insert_array['custom_face'] = 1;
			}
			$query['chattransferfileinfo'] = $insert_array;
            $autoid = POP::exe('[@@:UM chattransferfileinfo][@@:QU save]',$query);

			if($autoid && ($upfile==1)){
				$fileurl = Router::url('im/getfile/?fid='.$autoid);
				$fileurl = "{IM:A}$fileurl{/IM:A}";
				echo "<script language=\"javascript\">parent.backAutoSendMsg(".$pid.",'".$language_transfer['FileUpdateToServer']."。\\r\\n".$language_basic['ClickForDownload']."：\\r\\n".$fileurl."');</script>";
			}elseif($autoid && ($upfile==2)){
				$fileurl = "{img:".$this->base.'/'.$upfileAry['filename']."/}";
				echo "<script language='javascript'>parent.backSubmitImg('".$fileurl."');</script>";
			}else{
				echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['TransferFileOff']."');</script>";
				exit;
			}
		}else{
			echo "<script language=\"javascript\">parent.backTransferFileError('".$language_transfer['TransferFileOff']."');</script>";
			exit;
		}		
        exit;
    }
	
	
	public function getpeerid() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		
		$pals_id = short_check(Request::get_args('pals_id'));
		if(!$pals_id) {
			exit('-1');
		}
		$player_ids = get_player_ids($uid,$pals_id); 
		$session_info = $this->get_session_info($player_ids);

		$player_ids = array_nullclear(explode(',',$session_info['player_ids']));
		$video_ids = explode(',',$session_info['video_peerid']);
		foreach($player_ids as $key => $value) {
			if($value==$pals_id) {
				$peerid = $video_ids[$key-1];
			}
		}
		if($peerid){
			echo $peerid;
		}else{
			echo '-1';
		}		
		exit;
	}	
	
	public function getvideostatus() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		/* post 数据处理 */
		$pals_id = Request::get_args("pals_id");

		if(is_numeric($pals_id)) {
			$player_ids = get_player_ids($uid,$pals_id); 
			
			$query = array(
				'conditions' => array('chatsession.player_ids' => $player_ids), 
				'fields' => array('chatsession.video_status'), 
			);
			$video_status = POP::exe('[@@:UM chatsession][@@:QU find:first]',$query);				
			echo $video_status['chatsession']['video_status'];
		}else{
			exit('-1');
		}
		exit;
	}	
	
	public function updatepeerid() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		$peerid = short_check(Request::get_args('peerid'));
		$calluser = short_check(Request::get_args('calluser'));
		$player_ids = get_player_ids($uid,$calluser); 
		$session_info = $this->get_session_info($player_ids);
		if($session_info) {
			$player_ids = array_nullclear(explode(',',$session_info['player_ids']));
			$video_peerid = $session_info['video_peerid'];
			$video_ids = explode(',',$video_peerid);
			foreach($player_ids as $key => $value) {
				if($value==$uid) {
					$video_ids[$key-1] = $peerid;		
				}
			}
			$video_ids = implode(',',$video_ids);
			$updates = array('video_peerid'=>$video_ids);
			$this->imUpdateSessionById($session_info['session_id'],$updates);
		}else{
			exit('-1');
		}		
		exit;
	}
	
	public function updatevideostatus() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		
		/* post 数据处理 */
		$pals_id = short_check(Request::get_args("pals"));
		$imaction = short_check(Request::get_args("imaction"));
		if(is_numeric($pals_id)) {
			$player_ids = get_player_ids($uid,$pals_id);			
			switch($imaction) {
				case 'p':
					$status = 1;
					$this->update_video_status($player_ids,$status);
					break;
				case 'g':
					$status = 2;
					$this->update_video_status($player_ids,$status);
					break;
				case 'c':
					$status = 0;
					$this->update_video_status($player_ids,$status);
					break;
			}
		} 			
		exit;
	}
	

	//更新个性签名
	public function updateintro() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		$intro = strip_tags(short_check(Request::get_args('intro')));

		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatuser'] = array('u_intro'=>$intro);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatuser.uid'=>$uid);		
		if(POP::exe('[@@:UM chatuser][@@:QU save]',$query)){
			echo stripcslashes($intro);
		}else{
			echo '-1';
		}		
		exit;
	}
	
	
	public function uploadheadimg() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
        Loader::import('lib.cuploadfull');
		$up = new upload();
		$up->set_field('headimg');
		$up->set_dir('uploadfiles/headimg/');//目录设置
		$up->set_thumb(40,40); 
		$fs = $up->execute();

		if($fs) {
			unlink($fs[0]['dir'].$fs[0]['name']);
			$headimg = $this->base.'/'.$fs[0]['dir'].$fs[0]['thumb'];
			//更新用户头像
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chatuser'] = array('u_ico'=>$headimg);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chatuser.uid'=>$uid);		
			POP::exe('[@@:UM chatuser][@@:QU save]',$query);
			echo "<script language=\"javascript\">parent.i_im_backChangeIco('".$headimg."');</script>";
		} else {
			exit('-1');
		}		
		exit;
	}		
	
	
	public function onlineTime() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');		
		Loader::import('lib.ctime');
		$ctime = new ctime();
		$time_stamp = $ctime->time_stamp();	

		$userinfo = $this->get_user_info($uid);
		$last_time = $userinfo['last_time'];
		$online_time = $userinfo['online_time'];
		$online_time = $time_stamp-$last_time+$online_time;

		// 更新最后动作时间，在线时间
		$this->im_update_online_time($uid,$time_stamp,$online_time);

		echo $online_time;		
		exit;
		
	}		
	

	public function delFriends() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');		
		$delids = short_check(Request::get_args('ids'));
		if($delids) {
			$delids = array_nullclear(explode(",",$delids));
		} else {
			exit('-1');
		}
		$del_success = array();

		foreach($delids as $pals_id) {
			$player_ids = get_player_ids($uid,$pals_id);
			$session_info = $this->get_session_info($player_ids);
			if($session_info) {
			    //删除聊天记录
				$session_id = $session_info['session_id'];
				$query = array('conditions'=>array('chattxt.session_id' => $session_id));			
				$delText = POP::exe('[@@:UM chattxt][@@:QU del]',$query);
				//删除好友关系记录
				$query = array('conditions'=>array('chatsession.session_id' => $session_id));			
				$delSession = POP::exe('[@@:UM chatsession][@@:QU del]',$query);
			}
			$query = array('conditions'=>array('chatpals.host_id' => $uid,'chatpals.pals_id' => $pals_id));			
			$delPals = POP::exe('[@@:UM chatpals][@@:QU del]',$query);			
			$del_success[] = $pals_id;
		}
		echo chat_json_encode($del_success);		
		exit;
	}	
	
	
	public function getCustomGroup() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');		
		$customGroup = $this->imGetCustomGroup($uid);
		if($customGroup) {
			echo chat_json_encode($customGroup);
			exit;
		}else{
			exit('-1');
		}		
	}	
	
	public function moveFriends() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		
		$ids = short_check(Request::get_args('ids'));
		$gid = short_check(Request::get_args('gid'));
		if($ids) {
			$ids = array_nullclear(explode(",",$ids));
		} else {
			exit('-1');
		}
		!$ids && exit('-1');
		//$ids = implode(',',$ids);
		if(!$gid && $gid!=='0' && $gid!==0) {
			exit('-1');
		}
		
		if($gid=='-1') {
			//移动到陌生人	
			$query = array('conditions'=>array('chatpals.pals_id' => $pals_id,'chatpals.host_id' => $uid));			
			$moveFriend = POP::exe('[@@:UM chatpals][@@:QU del]',$query);
		}else{
		    //移动好友
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chatpals'] = array('groupId'=>$gid);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chatpals.pals_id'=>$ids,'chatpals.host_id'=>$uid);		
			$moveFriend = POP::exe('[@@:UM chatpals][@@:QU save]',$query);			
		}


		if($moveFriend) {
			echo chat_json_encode($ids);
		}else{
			exit('-1');
		}	
        exit;
	
	}	
	
	public function newCustomGroup() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');	
		$newGroupName = short_check(Request::get_args('groupName'));
		if(!$newGroupName) {
			exit('-1');
		}	
		$insertArray = array(
			'uid'	=>	$uid,
			'groupName'	=>	$newGroupName,
		);
		$query['chatcustomgroup'] = $insertArray;
		$groupid = POP::exe('[@@:UM chatcustomgroup][@@:QU save]',$query);
		if($groupid>0) {
			echo chat_json_encode(array('gid'=>$groupid,'gname'=>$newGroupName));
			exit;
		}else{
			exit('-1');
		}		
	}	

	public function updateCustomGroup() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');

		$gid = short_check(Request::get_args('gid'));
		$gname = short_check(Request::get_args('gname'));

		!$gid && exit('-1');
		!$gname && exit('-1');

		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatcustomgroup'] = array('groupName'=>$gname);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatcustomgroup.id'=>$gid,'chatcustomgroup.uid'=>$uid);		
		if(POP::exe('[@@:UM chatcustomgroup][@@:QU save]',$query)) {
			exit('1');
		}else{
			exit('-1');
		}		
	}	
	
	public function delCustomGroup() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');

		$gid = short_check(Request::get_args('gid'));
		$gname = short_check(Request::get_args('gname'));
        !$gid && exit('-1');
		
		//移动组内成员
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatpals'] = array('groupId'=>0);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatpals.host_id'=>$uid,'chatpals.groupId'=>$gid);	
		POP::exe('[@@:UM chatpals][@@:QU save]',$query);		
		//删除分组
		$query = array('conditions'=>array('chatcustomgroup.id' => $gid,'chatcustomgroup.uid' => $uid));			
		$delinfo = POP::exe('[@@:UM chatcustomgroup][@@:QU del]',$query);		
		if($delinfo) {
			exit('1');
		}else {
			exit('-1');
		}			
	}
	
	
	public function setCondition() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');

		$addcon = short_check(Request::get_args('addcon'));
		$im_question = short_check(Request::get_args('im_question'));
		$im_answer = short_check(Request::get_args('im_answer'));
		!$addcon && exit('-1');
		switch($addcon) {
			case 1:
				$safeData['chatuser'] = array('addFriends'=>$addcon);
				break;
			case 2:
			    $safeData['chatuser'] = array('addFriends'=>$addcon,'question'=>$im_question,'answer'=>$im_answer);
				break;
			case 3:
				$safeData['chatuser'] = array('addFriends'=>$addcon);
				break;
			default:
				exit('-1');
		}
		//移动组内成员
		$query  = array();		
		$query['keyid'] = true;				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatuser.uid'=>$uid);	
		$updateinfo = POP::exe('[@@:UM chatuser][@@:QU save]',$query);		
		if($updateinfo) {
			echo chat_json_encode(array('addcon'=>$addcon,'question'=>$im_question,'answer'=>$im_answer)); 
		}else{
			echo '-1';
		}		
		exit;
	}	
	
	
	public function getStranger() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }		
		$uverifycode = $this->C_session->read('pspim.uverifycode');

		
		//获取所有联系过的会员
		$allContacted = $this->imGetAllContactedUsers($uid);
		//获取所有好友
		$allFriends = $this->get_friend_list($uid);
		
		if(!$allFriends) {
			$allFriends = array();
		}
		$allFriendsId = array();
		foreach($allFriends as $v) {
			$allFriendsId[] = $v['pals_id'];
		}	
		$strangers = array();
		foreach($allContacted as $key => $value) {
			$player_ids = str_replace(",".$uid.",",'',$value['player_ids']);			
			$player_ids = array_nullclear(explode(',',$player_ids));
			$player_id = isset($player_ids[0]) ? $player_ids[0] : $player_ids[1];
			if($player_id && !in_array($player_id,$allFriendsId)) {
				$strangers[] = $player_id;
			}
		}

		!$strangers && exit('-1');
		$strangerids = implode(',',$strangers);

		$strangersinfo = $this->get_group_friend_list($strangerids);

		if($strangersinfo &&is_array($strangersinfo)) {
			echo chat_json_encode($strangersinfo);
		}else{
			exit('-1');
		}		
	}
	
	public function updateContacted() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }		
		$uverifycode = $this->C_session->read('pspim.uverifycode');
        $contactuid = short_check(Request::get_args('uid'));
		
		$userinfo = $this->get_user_info($uid);

		$contacted = $userinfo['contacted'];
		$length = strrpos($contacted,',') ? strrpos($contacted,',') : strlen($contacted);

		$contacted = substr($contacted,0,$length);

		if($contacted && $contactuid) {
			$contacted = $contactuid.','.$contacted;
		}elseif(!$contacted && $contactuid){
			$contacted = $contactuid;
		}

		!$contacted && exit('-1');
		$contactedAry = explode(',',$contacted);

		if(count($contactedAry)>10) {
			array_pop($contactedAry);
		}
		$contacted = implode(',',$contactedAry);

		$this->imUpdateUserInfo($uid,array('contacted'=>$contacted));
		$contactedUsers = $this->get_group_friend_list($contacted);
		if($contactedUsers) {
			echo chat_json_encode($contactedUsers);
		}else{
			exit('-1');
		}
        exit;
		
	}
	

	public function searchGroup() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }		
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		
		
		$s = Request::get_args("s");	
		if(!empty($s)) {
			$keyword = short_check($s);
		} else {
			exit('-1');
		}
		$searchgroup = $this->imSearchGroupByKeyWord($keyword);
		if($searchgroup) {
			$return = array();
			foreach($searchgroup as $value) {
				$players = explode(',',$value['player_ids']);
				$isin = in_array($uid,$players) ? 1 : 0;
				$return[] = array('gid'=>$value['session_id'],'gname'=>$value['group_name'],'ownerid'=>$players[1],'isin'=>$isin);
			}
			echo chat_json_encode($return);
		} else {
			exit('-1');
		}
		
	}
	
	public function serachUser() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		$s = Request::get_args("s");
		if(!empty($s)) {
			$keyword = short_check($s);
		} else {
			exit('-1');
		}
		$userinfo = $this->get_user_info_by_name($keyword);
		if($userinfo) {
			$return = array();
			foreach($userinfo as $value) {
				$return[] = array(
								'pals_id' => $value['uid'],
								'pals_name' => $value['u_name'],
								'pals_ico' => $value['u_ico'],
								'line_status' => $value['line_status']
							);
			}
			echo chat_json_encode($return);
			exit;
		} else {
			exit('-1');
		}		
		
	}	

	public function delmsg() {
		// 通过当前SESSION获取 当前用户信息
		$uid = $this->C_session->read('pspim.uid');
		if(!$uid) { exit('-1'); }
		$uverifycode = $this->C_session->read('pspim.uverifycode');
		$tid = short_check(Request::get_args('tid'));
		$rid = short_check(Request::get_args('rid'));
		$pid = short_check(Request::get_args('pid'));	
	
		$del_success = array();
		if($pid) {
			if(is_numeric($pid)) {		//删除分页消息
				$msginfo = $this->imGetSingleMsg($pid);
				if($msginfo) {
					if(strpos($msginfo['player_ids'],','.$uid.',')===false && $msginfo['multi_chat']!='0') {
						exit('-1');
					}
					$delinfo = $this->imDelMsgPage($pid);
					$delinfo && exit('1');
				}
			} elseif(strpos('imWin_',$pid)===false && $msginfo['multi_chat']!='0') {		//删除全部记录
				$pals_id = str_replace('imWin_','',$pid);
				$player_ids = get_player_ids($uid,$pals_id);
				$session_info = $this->get_session_info($player_ids);
				if($session_info) {
					$delstatus = $this->imDelWholeMsg($session_info['session_id'],$player_ids);
					$delstatus && exit('1');
				}
			}
		} else {	//删除单条记录
			if(!is_numeric($tid) || !is_numeric($rid)) {
				exit('-1');
			}
			$msginfo = $this->imGetSingleMsg($tid);
			if($msginfo) {
				if(strpos($msginfo['player_ids'],','.$uid.',')===false) {
					exit('-1');
				}
				$msg = preg_replace("/<ct_".$rid.">(.+?)<\/ct_".$rid.">/",'',$msginfo['txt_content']);

				$msg = str_replace("'","\'",$msg);
				if($msg) {
					$update = array('txt_content'=>$msg);
					$updateinfo = $this->imUpdateMsg($tid,$update);
					echo $updateinfo?'1':'-1';
				} else {
					if($msginfo['using']==0) {
						$delpage = $this->imDelMsgPage($tid);
						echo $delpage?'1':'-1';
					}
				}	
			}
		}
		exit('-1');

	
	}	
	
	//更新视频链接状态
	function update_video_status($player_ids,$status,$uid=0){
		if($uid){
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chatsession'] = array('video_status'=>$status,'from_user_id'=>$uid);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chatsession.player_ids'=>$player_ids,'chatsession.group_name'=>'');			
		}else{
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chatsession'] = array('video_status'=>$status);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chatsession.player_ids'=>$player_ids,'chatsession.group_name'=>'');		
		}
		POP::exe('[@@:UM chatsession][@@:QU save]',$query);
	}	
	
	//获取单页聊天记录
	function imGetSingleMsg($tid) {
		$query = array(
			'conditions' => array('chattxt.id' => $tid), 
			'fields' => array('chattxt.*'), 
		);
		$rowset = POP::exe('[@@:UM chattxt][@@:QU find:first]',$query);	
		return $rowset['chattxt'];
	}	
	
	//删除消息分页
	function imDelMsgPage($tid) {
		$query = array('conditions'=>array('chattxt.id' => $tid));			
		return POP::exe('[@@:UM chattxt][@@:QU del]',$query);		
	}	
	//删除全部聊天记录
	function imDelWholeMsg($session_id,$player_ids) {
		$query = array('conditions'=>array('chattxt.session_id' => $session_id,'chattxt.player_ids' => $player_ids,'chattxt.multi_chat' => 0));			
		return POP::exe('[@@:UM chattxt][@@:QU del]',$query);		
	}	
	
	//跟新聊天记录
	function imUpdateMsg($tid,$update) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chattxt'] = $update;				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chattxt.id'=>$tid);	
		return POP::exe('[@@:UM chattxt][@@:QU save]',$query);	
	}	
	//更新session信息
	function imUpdateSessionById($sessionid,$sessioninfo) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatsession'] = $sessioninfo;				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatsession.session_id'=>$sessionid);		
		return POP::exe('[@@:UM chatsession][@@:QU save]',$query);	
	}	
	// 获取api好友关系信息
	function get_api_pals_list() {
        $session_uid = $this->C_session->read('Auth.user.id');
        if(!$session_uid) {exit();}	//没有session_uid退出	
        $getPalsListSql = 1;
		
		if($getPalsListSql) {
			$query = array(
				'conditions' => array('palsmine.user_id' => $session_uid), 
				'fields' => array('palsmine.*'), 
			);
			$rowset = POP::exe('[@@:UM palsmine][@@:QU find:all]',$query);			
			$array = array();
			$i = 0;
			foreach($rowset as $key=>$value) {
			    $value = $value['palsmine'];
				if(!strstr($value['pals_ico'],'http://')) {
					$value['u_ico'] = $value['pals_ico'];
				}
				$array[$i]['uid'] = $value['pals_id'];
				$array[$i]['u_name'] = $value['pals_name'];
				$array[$i]['u_intro'] = $value['u_intro'];
				$array[$i]['u_ico'] = $value['u_ico'];
				$i++;
			}
			return $array;
		} else {
			return '';
		}
	}	
	
	
	//更新用户信息
	function imUpdateUserInfo($uid,$userinfo) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatuser'] = $userinfo;				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatuser.uid'=>$uid);	
		return POP::exe('[@@:UM chatuser][@@:QU save]',$query);
    }	
	
	function get_user_info_by_name($uname) {
		$query = array(
			'conditions' => array('chatuser.u_name' => $uname), 
			'fields' => array('chatuser.*'), 
		);
		$row = POP::exe('[@@:UM chatuser][@@:QU find:all]',$query);	
		$uarray = array();
		foreach($row as $k =>$v) {
		    $uarray[$k] =  $v['chatuser'];
		}	
		return $uarray;
	}	

	//获取自定义好友分组
	function imGetCustomGroup($uid) {
		$query = array(
			'conditions' => array('chatcustomgroup.uid' => $uid), 
			'fields' => array('chatcustomgroup.*'), 
		);
		$row = POP::exe('[@@:UM chatcustomgroup][@@:QU find:all]',$query);
		$customGroup = array();
		foreach($row as $k =>$v) {
		    $customGroup[$k] =  $v['chatcustomgroup'];
		}	
		return $customGroup;
	}
	
	//搜索讨论组
	function imSearchGroupByKeyWord($keyword) {
		$query = array(
			'conditions' => array('chatsession.group_name' => "%$keyword%"), 
			'fields' => array('chatsession.*'), 
		);
		$row = POP::exe('[@@:UM chatsession][@@:QU find:all]',$query);	
		$uarray = array();
		foreach($row as $k =>$v) {
		    $uarray[$k] =  $v['chatsession'];
		}	
		return $uarray;	
	}	
	
	
	// 更新用户最后动作时间
	function update_user_last_time($uid,$time_stamp) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatuser'] = array('last_time'=>$time_stamp);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatuser.uid'=>$uid);	
		return POP::exe('[@@:UM chatuser][@@:QU save]',$query);
	}	
    function im_update_online_time($uid,$time_stamp,$online_time) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatuser'] = array('last_time'=>$time_stamp,'online_time'=>$online_time);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatuser.uid'=>$uid);		
		return POP::exe('[@@:UM chatuser][@@:QU save]',$query);
    }		
	// 更新超时用户为离线
	function update_user_to_offline($uids) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatuser'] = array('line_status'=>0);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatuser.uid'=>$uids);			
		if(	POP::exe('[@@:UM chatuser][@@:QU save]',$query)){
			$time = time();
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chatpals'] = array('line_status'=>0);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chatpals.pals_id'=>$uids);	
			return POP::exe('[@@:UM chatpals][@@:QU save]',$query);
		} else {
			return false;
		}	
	}	
	
	
	// 获取已超时的用户
	function get_timeout_user($time_stamp) {
		$last_time = $time_stamp- Param::read('im.offline_time');		
		$query = array(
			'conditions' => array('chatuser.line_status >' => 0,'chatuser.last_time <' => $last_time), 
			'fields' => array('chatuser.uid'), 
		);
		$rowset = POP::exe('[@@:UM chatuser][@@:QU find:all]',$query);		
		$array = array();
		if($rowset) {
			foreach($rowset as $value) {
				$array[] = $value['chatuser']['uid'];
			}
			return $array;
		} else {
			return false;
		}
	}	

	// 添加一个好友
	function insert_friend_info($array) {
        $query['chatpals'] = $array;
		return POP::exe('[@@:UM chatpals][@@:QU save]',$query);
	}	
	
	// 获取好友列表
	function get_friend_list($uid) {
		$query = array(
				'joins' => array(
				array('type'=>'left','table'=>'chatuser','conditions'=>array('chatpals.pals_id' =>'chatuser.uid')),					
				),
				'fields' => array('chatpals.*','chatuser.u_intro'),
				'conditions' => array('chatpals.host_id' =>$uid),
			);	
	    $rs = POP::exe('[@@:UM chatpals][@@:QU find:all]',$query);
		if(!$rs) { return false;}
		$online = array();
		$notline = array();
		foreach($rs as $key=>$value) {
		    $value['chatpals']['pals_intro'] = $value['chatuser']['u_intro'];
			$value = $value['chatpals'];
			if($value['line_status']==0 || $value['line_status']==2) {
				$notline[] = clear_array_numkey($value);
			} else {
				$online[] = clear_array_numkey($value);
			}
		}
		return array_merge($online,$notline);
	}	
	function get_group_friend_list($ids) {
	    $ids = explode(',',$ids);
		$query = array(
			'conditions' => array('chatuser.uid' => $ids), 
			'fields' => array('chatuser.*'), 
		);
		$rs = POP::exe('[@@:UM chatuser][@@:QU find:all]',$query);	
		if(!$rs) { return false;}
		$online = array();
		$notline = array();
		foreach($rs as $key=>$value) {
		    $value = $value['chatuser'];
			if($value['line_status']=='0' || $value['line_status']=='2') {
				$notline[] = array(
					'pals_id' => $value['uid'],
					'pals_name' => $value['u_name'],
					'pals_ico' => $value['u_ico'],
					'line_status' => $value['line_status'],
					'pals_intro' => $value['u_intro'],
				);
			} else {
				$online[] = array(
					'pals_id' => $value['uid'],
					'pals_name' => $value['u_name'],
					'pals_ico' => $value['u_ico'],
					'line_status' => $value['line_status'],
					'pals_intro' => $value['u_intro'],
				);
			}
		}
		return array_merge($online,$notline);
	}	
	
	// 根据player_ids获取session_info
	function get_session_info($player_ids) {
		$query = array(
			'conditions' => array('chatsession.player_ids' => $player_ids,'chatsession.group_name' =>''), 
			'fields' => array('chatsession.*'), 
		);
		$row = POP::exe('[@@:UM chatsession][@@:QU find:first]',$query);	
		return $row['chatsession'];		
	}	
	
	// 根据session_id获取session_info
	function  get_session_info_bysessionid($session_id) {
		$query = array(
			'conditions' => array('chatsession.session_id' => $session_id), 
			'fields' => array('chatsession.*'), 
		);
		$row = POP::exe('[@@:UM chatsession][@@:QU find:first]',$query);	
		return $row['chatsession'];	
	}	
	
	// 更新 init_pagect_position
	function update_init_pagect_position($session_id,$readed_pagect_position) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatsession'] = array('init_pagect_position'=>$readed_pagect_position);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatsession.session_id'=>$session_id);	
		return POP::exe('[@@:UM chatsession][@@:QU save]',$query);	
	}	
	
	// 创建新的session_info
	function insert_new_seesion_info($player_ids) {
		$pagect_position = get_init_pagect_position($player_ids);
		$insert_array = array(
			'player_ids' => $player_ids,
			'page_num' => '1',
			'ct_num' => '0',
			'init_pagect_position' => $pagect_position,
			'readed_pagect_position' => $pagect_position,
			'session_code' => mk_code(),
		);
		$query['chatsession'] = $insert_array;
		$inid = POP::exe('[@@:UM chatsession][@@:QU save]',$query);
		if($inid) {
			$insert_array['session_id'] = $inid;
			return $insert_array;
		} else {
			return false;
		}
	}	
	// 创建新的txt_info
	function insert_new_txt_info($player_ids,$session_id,$multi_chat=0) {
		$multi_chat = $multi_chat ? 1 : 0;
		$insert_array = array(
			'player_ids' => $player_ids,
			'multi_chat' => $multi_chat,
			'txt_content' => '',
			'txt_length' => 0,
			'txt_pagenum' => 1,
			'txtlog_pageview' => $player_ids,
			'session_id' => $session_id,
		);
		$query['chattxt'] = $insert_array;
		$inid = POP::exe('[@@:UM chattxt][@@:QU save]',$query);		
		if($inid) {
			return $insert_array;
		} else {
			return false;
		}
	}	
	
	// 发送信息 用户信息
	function post_txt($player_ids,$txt_content,$txt_length) {	
		$sql ="[@@:UM chattxt][@@:QU update][_update][_table chattxt][_set txt_content = CONCAT(txt_content,'<ct_',txt_ctnum,'>$txt_content</ct_',txt_ctnum,'>'), txt_length=txt_length+'$txt_length', txt_ctnum=txt_ctnum+1][_where player_ids='$player_ids' and multi_chat='0' ORDER BY txt_pagenum DESC LIMIT 1 ]";			
		return POP::exe($sql);
	}	

	// 发送信息 群组信息
	function post_txt_bysessionid($session_id,$txt_content,$txt_length) {
		$sql ="[@@:UM chattxt][@@:QU update][_update][_table chattxt][_set txt_content = CONCAT(txt_content,'<ct_',txt_ctnum,'>$txt_content</ct_',txt_ctnum,'>'), txt_length=txt_length+'$txt_length', txt_ctnum=txt_ctnum+1][_where session_id='$session_id' ORDER BY txt_pagenum DESC LIMIT 1 ]";			
		return POP::exe($sql);	
	}	
	
	// 更新chat_session ct_num	// 一对一用户
	function update_session_ctnum($player_ids) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatsession'] = array('ct_num +'=>1);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatsession.player_ids'=>$player_ids,'chatsession.group_name'=>'');			
		return POP::exe('[@@:UM chatsession][@@:QU save]',$query);
	}
	// 群组用户
	function update_session_ctnum_bysessionid($session_id) {
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatsession'] = array('ct_num +'=>1);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatsession.session_id'=>$session_id);			
		return POP::exe('[@@:UM chatsession][@@:QU save]',$query);	
	}
	
	
	// 获取用户信息
	function get_user_info($uid) {
		$query = array(
			'conditions' => array('chatuser.uid' => $uid), 
			'fields' => array('chatuser.*'), 
		);
		$row = POP::exe('[@@:UM chatuser][@@:QU find:first]',$query);	
		return $row['chatuser'];
	}
	// 添加一个新用户信息
	function insert_user_info($array) {	
		$temp = array();
		$temp['chatuser'] = $array ;				
		return POP::exe('[@@:UM chatuser][@@:QU save]',$temp);
	}	
	
	// 更新当前用户所读到的位置
	function update_readed_pagect_position($uid,$array) {
		if($array) {
			$ex2 = array_nullclear(explode(",",$array['player_ids']));
			$ex3 = explode(",",$array['readed_pagect_position']);
			foreach($ex2 as $k=>$v) {
				if($v==$uid) {
					$ex3[$k-1] = $array['page_num']."->".$array['ct_num'];
				}
			}
			$readed_pagect_position = implode(",",$ex3);
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chatsession'] = array('readed_pagect_position'=>$readed_pagect_position);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chatsession.session_id'=>$array['session_id']);			
			return POP::exe('[@@:UM chatsession][@@:QU save]',$query);			
		}
	}

	// 聊天记录自动拆分
	function split_txt_content($split_arr) {
		foreach($split_arr as $value) {
			// 更新老记录为不使用记录
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chattxt'] = array('using'=>0);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chattxt.id'=>$value['id']);			
			POP::exe('[@@:UM chattxt][@@:QU save]',$query);			
			// 插入新记录
			$value['id'] = '';
			$query  = array();				
			$query['chattxt'] = $value;				
			if(POP::exe('[@@:UM chattxt][@@:QU save]',$query)) {
				$query  = array();		
				$query['keyid'] = true;
				$safeData['chatsession'] = array('page_num'=>$value['txt_pagenum'],'ct_num'=>0);				
				$query['set'] = $safeData;	
				$query['conditions'] = array('chatsession.session_id'=>$value['session_id']);			
				POP::exe('[@@:UM chatsession][@@:QU save]',$query);			
			}
		}
		return ;
	}	
	//数据修复
	function imIsExistTxt($session_id) {
		$query = array(
			'conditions' => array('chattxt.session_id' => $session_id), 
			'fields' => array('chattxt.*'), 
		);
		$row = POP::exe('[@@:UM chattxt][@@:QU find:first]',$query);	
		return $row['chattxt'];	
	}	
	
	// 改变当前状态
	function change_status($v,$uid) {
		$time = time();
		$query  = array();		
		$query['keyid'] = true;
		$safeData['chatpals'] = array('line_status'=>$v);				
		$query['set'] = $safeData;	
		$query['conditions'] = array('chatpals.pals_id'=>$uid);		
		if(POP::exe('[@@:UM chatpals][@@:QU save]',$query)	){
			$query  = array();		
			$query['keyid'] = true;
			$safeData['chatuser'] = array('line_status'=>$v,'last_time'=>$time);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('chatuser.uid'=>$uid);			
			return POP::exe('[@@:UM chatuser][@@:QU save]',$query);
		} else {
			return false;
		}
	}	
	
	//获取所有聊过天的会员
	function imGetAllContactedUsers($uid) {
		$player_ids = ",$uid,";
		$sql ="[@@:UM chatsession][@@:QU select][_select chatsession.* ][_from][_table chatsession:yes][_where group_name='' and instr(player_ids,'$player_ids') ]";		
		$rows = POP::exe($sql);	
		$uarray = array();
		foreach($rows as $k =>$v) {
		    $uarray[$k] =  $v['chatsession'];
		}	
		return $uarray;
	}	
	
    // 获取群组信息
    function get_group_list($uid) {

		$sql ="[@@:UM chatsession][@@:QU select][_select chatsession.* ][_from][_table chatsession:yes][_where group_name!='' and instr(player_ids,',$uid,') ]";			
		$rows = POP::exe($sql);	

		$array = array();
		foreach($rows as $k=>$v) {
		    $v = $v['chatsession'];
			$p_value = array_nullclear(explode(",",$v['player_ids']));
			$array[$k]['host_id'] = $uid;
			$array[$k]['pals_id'] = "g_".$v['session_id'];
			$array[$k]['group_name'] = $v['group_name'];
			$array[$k]['pals_name'] = $v['group_name'];
			$array[$k]['pals_ico'] = $this->base."images/talk.gif";
			$array[$k]['line_status'] = "1";
			$array[$k]['num'] = count($p_value);
			$array[$k]['group_mid'] = $p_value[1];
		}
		return $array;
    }
	
	// 获取有新消息的好友列表
	function get_newmsg_friend_list($uid) {
		$player_ids = ",$uid,";
		$sql ="[@@:UM chatsession][@@:QU select][_select chatsession.* ][_from][_table chatsession:yes][_where  instr(player_ids,'$player_ids') ]";			
		$rs = POP::exe($sql);		
		$array = array();
		if($rs) {
			foreach($rs as $key=>$value) {
			    $value = $value['chatsession'];
				if($pagect = check_new_message($uid,$value)) {
					$value['page'] = $pagect[0];
					$value['ct'] = $pagect[1];
					$array[] = $value;
				}
			}
		}
		return $array;
	}	
	// 用户创建一个新组
	function create_new_group($uid,$groupname,$m) {
		$insert_session_array = array(
			'player_ids' => ','.$uid.',',
			'page_num' => 1,
			'ct_num' => 0,
			'init_pagect_position' => '1->0',
			'readed_pagect_position' => '1->0',
			'group_name' => $groupname,
			'session_code' => mk_code(),
		);
		if($m=='meeting'){
			$insert_session_array['contact_status'] = ','.$uid.'->1,';
		}
        $query['chatsession'] = $insert_session_array;
        $session_id = POP::exe('[@@:UM chatsession][@@:QU save]',$query);
		if($session_id) {
			$this->insert_new_txt_info(','.$uid.',',$session_id,1);
		} else {
			return false;
		}
		return $session_id;
	}		
	
}
// 格式聊天记录到数组
function format_message($pagect,$txt) {
	$array = array();
	if($txt['txt_pagenum']>$pagect[0] || $pagect[1]==0) {
		preg_match_all("/<ct_([0-9]+)>([0-9]+){([0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+)}(.+?)<\/ct_[0-9]+>/",$txt['txt_content'],$out);
	} else {
		$ex_result = explode("<ct_".($pagect[1]+1).">",$txt['txt_content']);
		if(!isset($ex_result[1]))$ex_result[1]='';
		preg_match_all("/<ct_([0-9]+)>([0-9]+){([0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+)}(.+?)<\/ct_[0-9]+>/","<ct_".($pagect[1]+1).">".$ex_result[1],$out);
	}
	foreach($out[1] as $key=>$value) {
		$array[$key] = array(
			'rid'=>	$out[1][$key],
			'id' => $out[2][$key],
			'time' => $out[3][$key],
			'txt' => preg_replace("/{:(\d+):}/i","<span class='smile_$1'></span>",$out[4][$key])
		);
	}
	return $array;
}
// 检查是否有新消息
function check_new_message($uid,$session_info) {
	$r_arr = explode(",",$session_info['readed_pagect_position']);
	$p_arr = explode(",",$session_info['player_ids']);
	if(!in_array($uid,$p_arr)) {
		return false;
	}
	$k = '';
	foreach($p_arr as $key=>$value) {
		if($value==$uid) {
			$k = ($key-1);
		}
	}
	$pagect = explode("->",$r_arr[$k]);
	if($session_info['page_num'] > $pagect[0] || $session_info['ct_num'] > $pagect[1] || ($session_info['video_status']==1)) {
		return $pagect;
	} else {
		return false;
	}
}
// 初始化pagect_position
function get_init_pagect_position($player_ids) {
	$num = back_player_num($player_ids);
	$newarray = array();
	for($i=0; $i<$num; $i++) {
		$newarray[] = '1->0';
	}
	return implode(",",$newarray);
}

// 初始化pagect_position
function back_player_num($player_ids) {
	return count(explode(",",$player_ids))-2;
}
// 获取player_ids
function get_player_ids($uid,$pals_id) {
	$newarray = array();
	if(strstr($pals_id,',')){
		$explode = explode(",",$pals_id);
		$newarray = $explode;
		if(!in_array($uid,$newarray)) {
			$newarray[] = $uid;
		}
	} else {
		$newarray = array($uid,$pals_id);
	}
	$newarray = array_nullclear($newarray);
	sort($newarray);
	return ','.implode(",",$newarray).',';
}
// 清除数组里值为空的值
function array_nullclear($array) {
	$newarray = array();
	foreach($array as $k=>$v){
		if($v) {
			$newarray[$k] = $v;
		}
	}
	return $newarray;
}
// 随机生成code
function mk_code($num=6) {
	$strSeed = "123456789abcdefghijklmnprstuvwxyz";
    $bgnIdx = 0;
    $endIdx = strlen($strSeed)-1;

    $code = "";
	for($i=0; $i<$num; $i++) {
		$curPos = rand($bgnIdx, $endIdx);
		$code .= substr($strSeed, $curPos, 1);
	}

	return $code;
}
// 加密
function mk_md5($s_code,$u_code) {
	$verify_prefix = Param::read('im.verify_prefix');
	return md5($s_code.$u_code.$verify_prefix);
}
// Json 处理
function chat_json_encode($array) {
	return json_encode($array);
}

function chat_json_decode($value) {
	return json_decode($value);
}
// 清除数组里下标为数字的值
function clear_array_numkey($array) {
	if(!is_array($array)) {return false;}
	$newarray = array();
	foreach($array as $key=>$value) {
		if(!is_numeric($key)) {
			$newarray[$key] = $value;
		}
	}
	return $newarray;
}
function short_check($str) {  
   	$MaxSlen=300;//限制短输入项最多300个字符
	$str = LenLimit($str,$MaxSlen);
//     $str = str_replace("\'", "", $str); 
//     $str = str_replace("\\", "", $str); 
//     $str = str_replace("#", "", $str); 
//     $str = str_replace("=", "", $str);
//     $str = str_replace(" ", "", $str);
    $str= htmlspecialchars($str);
   	return trim($str); 
}
//限制输入字符长度，防止缓冲区溢出攻击
function LenLimit($Str,$MaxSlen){
    if(isset($Str{$MaxSlen})){
        return " ";
    }else{
        return $Str;
    }
}
//输出404页面
function echo404(){
	$nopage = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
	$nopage .= '<html><head><title>页面不存在</title></head><body style="background:#F0F0F0;">';
	$nopage .= '<div style="width:250px;height:80px; border:1px solid #BBBBBB; margin:100px auto; text-align:center;padding:55px 0 0 0; background:#FFFFFF;">出错了，您访问的页面不存在...</div>';
	$nopage .= '</body></html>';
	echo $nopage;
	exit;
}
?>